<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="addTradeMark">添加</el-button>
    <el-table :data="trademark.records" style="width: 100%; margin: 20px 0" border>
      <el-table-column type="index"  label="序号" width="80" align="center"> </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width" align="center">
      </el-table-column>
      <el-table-column prop="prop" label="品牌LOGO" width="width" align="center">
        <template slot-scope="{row,$index}">
         <img :src="row.logoUrl" style="width:100px"/>
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="width" align="center">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updataTradeMark(row)">修改</el-button>
            <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="考虑"
            icon="el-icon-delete"
            icon-color="#409eff"
            :title="`你确定删除${row.tmName}?`"
            @onConfirm="confirm(row)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="danger"
              style="margin: 0px 10px"
              icon="el-icon-delete"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align: center"
      @current-change="getTradeMarkInfo"
      @size-change="sizeHandler"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      prev-text="上一页"
      next-text="下一页"
      background
      :pager-count="5"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="99"
    >
    </el-pagination>
   <!-- 对话框 -->
    <el-dialog :title="tmForm.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible" ref="dialog">
  <el-form :model="tmForm" :rules="rules" ref="form">
    <el-form-item label="品牌名称" label-width="100px" prop="tmName">
      <el-input  autocomplete="off" v-model="tmForm.tmName"></el-input>
    </el-form-item>
    <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
      <el-upload
        class="avatar-uploader"
        action="/api/admin/product/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        drag
         ref="upload"
        >    
  <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" style="width:100%;height:100%">
  <i v-else class="el-icon-plus avatar-uploader-icon">支持拖拽</i>
</el-upload>
    </el-form-item>
  
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary"  @click="addOrUpdataTradeMark">确 定</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
//定义自定义校验规则
var checkTmName = (rule, value, callback) => {
  //value:自定义校验规则字段相应数值
  //callBack:校验字段以后,放行函数
  //rule:element提供对象,可以看到校验字段名、字段属性值是什么类型的
  //品牌校验规则:汉字{4,8}
  if (/^[\u4e00-\u9fa5]{4,8}$/.test(value)) {
    //代表验证通过
    callback();
  } else {
    callback(new Error("品牌名称4-8汉字"));
  }
};

//品牌LOGO自定义校验规则
const checkLogoUrl = (rule,value,cb)=>{
      //假装的校验规则
      if(value){
         cb();
      }else{
         cb(new Error('大哥请你选择品牌LOGO'))
      }
}
export default {
  data() {
    return {
      page:2,
      limit:3,
      trademark:{},
      dialogFormVisible: false,
      tmForm:{
        tmName:'',
        logoUrl:''
      },
       //表单验证规则
      rules: {
        //校验的字段
        tmName: [
          //自定义校验规则:validator用于设置校验规则  trigger:触发校验事件blur、change
          { required:true,validator: checkTmName, trigger: "blur" },
        ],
        //底下logoURL字段并非表单，trigger没有任何意义
        logoUrl: [{ required: true,validator: checkLogoUrl}],
      },
    }
  },
  
  mounted() {
    this.getTradeMarkInfo();
  },
  methods: {
   async getTradeMarkInfo(pager=1) {
     this.page = pager
      const {page,limit} = this
      let result = await this.$http.trademark.reqTradeMark(page,limit)
      if(result.code ==200){
        this.trademark = result.data
      }
    },
    sizeHandler(limit){
       this.limit = limit   
       this.getTradeMarkInfo();
    },
    handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.tmForm.logoUrl = res.data
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //添加品牌按钮
      addTradeMark(){
        this.tmForm ={tmName:'',logoUrl:''}
        this.dialogFormVisible = true
        this.$nextTick(() => {
        //获取上传图片的的组件的VC:关闭图片列表名字
        this.$refs.upload.clearFiles();
        this.$refs.form.resetFields();
      });
      } ,
      //对话框确定按钮
      addOrUpdataTradeMark() {
      //获取FOrm组件,全部验证规则通过以后在发请求
      this.$refs.form.validate(async (success) => {
        //全部验证成功干啥
        if (success) {
          //整理参数
          let data = this.tmForm;
          //发请求
          try {
            //添加|修改成功
            await this.$http.trademark.reqAddOrUpdateTradeMark(data);
            //关闭对话框
            this.dialogFormVisible = false;
            //再次获取添加|修改完毕以后最新品牌的数据
            //如果是修改留在当前页，如果是新增留在第一个
            this.getTradeMarkInfo(this.tmForm.id ? this.page : 1);
            //消息提示框插件
            this.$message({
              message: this.tmForm.id ? "修改品牌成功" : "新增品牌成功",
              type: "success",
            });
          } catch (error) {
            this.$message({
              message: this.tmForm.id ? "修改品牌失败" : "新增品牌失败",
              type: "error",
            });
          }
        } else {
          //验证有失败
          console.log("error submit!!");
          return false;
        }
      });
    },
      //取消
      cancel(){
       this.dialogFormVisible=false
      },
      //修改
      updataTradeMark(row){
        this.dialogFormVisible=true
        //每一次点击修改按钮的文件列表名清空
      this.$nextTick(() => {
        //获取上传图片的的组件的VC:关闭图片列表名字
        this.$refs.upload.clearFiles();
        //重置表单:使用初始值
        this.$refs.form.resetFields();
        //在修改数值
        this.tmForm = { ...row };
      });
       
      },
       async confirm(row){
         //发请求,通知服务器删除选中商品
      try {
        //删除成功,还要再次获取最新的品牌数据展示
        await this.$http.trademark.reqDeleteTradeMark(row.id);
        //判断删除以后留在那一页
        this.getTradeMarkInfo(
          this.trademark.records.length > 1 ? this.page : this.page - 1
        );
      } catch (error) {}
      }
      
  },
};
</script>

<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>